#include <time.h>

#include "soh.h"


/****************************************************************
This file contains the entry point to the program. Here parsing 
of input parameters and some preparatory work is performed.
****************************************************************/

int main( int argc, char* argv[], char* envp[] ){
	
	int i;
	int res;
	unsigned int port = 0;
	
	struct instance this = {
		.envp = envp,
		.sharePath  = NULL,
		.netTimeout = 1,
		.progs = NULL,
	};
	
	//parse arguments
	for( i = 1; i < argc; i++ ){
		
		//port
		if( !strcmp(argv[i], "-p") ){
			i++;
			if( i == argc || port ) goto l_help;
			res = sscanf( argv[i], "%u", &port );
			if( res != 1 ) goto l_help;
			if( !port || port > 65535 ){
				printf( "TCP port must be in range 1-65535.\n" );
				return 2;
			}
		
		//path to share
		}else if( !strcmp(argv[i], "-s" ) ){
			i++;
			if( i == argc || this.sharePath ) goto l_help;
			this.sharePath = argv[i];
		
		//override timeout
		}else if( !strcmp(argv[i], "-t") ){
			i++;
			if( i == argc ) goto l_help;
			res = sscanf( argv[i], "%u", &this.netTimeout );
			if( res != 1 ) goto l_help;
		}
	}
	
	//some check
	if( !port || !this.sharePath ) goto l_help;
	
	//init custom memory allocator
	res = customMallocInit();
	if( res ) return 1;
	
	//search avaliable utils
	res = searchUnixPrograms( &this );
	if( res ) return 1;
	
	//index share
	res = indexShare( &this );
	if( res ) return 1;
	
	//set current share id
	sprintf( this.shareId, "%li", time(NULL) );
	printf( "ShareID: %s\n", this.shareId );
	printf( "http://127.0.0.1:%i/%s/shareinfo\n", port, this.shareId );
	
	//start server
	res = startServer( &this, port );
	if( res ) return 1;
	
	return 0;
	
l_help:
	printf( 
		"Usage:\n"
		"  %s [options] -p <port> -s <share>\n\n"
		"  <port>        TCP port that http server will listen.\n"
		"  <share>       Path to file or directory which will be shared.\n\n"
		"Options:\n"
		"  -t <sec>      The time in seconds before the connection is reset if there\n"
		"                is no activity from the client. Default: 1.\n"
		"\n"
		, argv[0] 
	);
	
	return 2;
}
